<?php

namespace app\admin\controller;

use app\common\model\GoodsModel;
use app\common\model\StorageLogModel;
use app\common\model\StorageManageModel;
use app\common\model\StorageModel;
use cmf\controller\AdminBaseController;
use cmf\lib\Storage;
use think\Db;
use think\db\Query;
use think\Request;

class GoodsController extends AdminBaseController
{
    public function index()
    {
        $list = GoodsModel::where(
            function (Query $query) {
                $query->where('isdel', 0);
                $param = $this->request->param();
                if (!empty($param['cid'])) {
                    $query->where('cid', $param['cid']);
                }

                if (!empty($param['keyword'])) {
                    $query->where('goods_name', 'like', "%{$param['keyword']}%");
                }

                if (!empty($param['price1'])) {
                    $query->where('goods_price', '>=', $param['price1']);
                }

                if (!empty($param['price2'])) {
                    $query->where('goods_price', '<=', $param['price2']);
                }
            })->order('id desc')->paginate()
            ->each(function ($v, $k) {
                $v['class'] = GoodsModel::getClass()[$v['cid']];
                $v['goods_master_image'] = cmf_get_image_url($v['goods_master_image']);
                $v['manage'] = StorageManageModel::where('id', $v['mid'])->value('name') ?: '平台';
                return $v;
            });

        $this->assign('class', GoodsModel::getClass());
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['image'])) {
                $this->error('封面图不能为空');
            }
            if (empty($param['goods_images'])) {
                $this->error('商品主图不能为空');
            }
            $param['goods_images'] = json_encode($param['goods_images']);
            if (GoodsModel::create($param)) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        }
        $class = GoodsModel::getClass();
        array_shift($class);
        $this->assign('class', $class);
        return $this->fetch();
    }

    public function edit($id)
    {
        $data = GoodsModel::where('id', $id)->find();
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['image'])) {
                $this->error('封面图不能为空');
            }
            if (empty($param['goods_images'])) {
                $this->error('商品主图不能为空');
            }
            $param['goods_images'] = json_encode($param['goods_images']);
            if ($data->save($param)) {
                $this->success('编辑成功');
            } else {
                $this->error('编辑失败');
            }
        }
        $data['goods_images'] = json_decode($data['goods_images'], true);
        $this->assign('class', GoodsModel::getClass());
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function setstatus($id, $status)
    {
        $log = StorageLogModel::where('goods_id', $id)->where('goods_num', '<>', 0)->find();
        if ($status == 1 && !$log) {
            $this->error('检测到该商品还没有库存信息，建议先修改库存再上架销售，库存至少为1');
        }
        if (GoodsModel::update(['goods_status' => $status, 'id' => $id])) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    public function del($id)
    {
        if (GoodsModel::update(['isdel' => 1, 'id' => $id])) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function stock(Request $request)
    {
        if ($request->isPost()) {
            list($goods_id, $sid, $field) = explode('-', $request->title);
            $value = $request->value;
            if ($value < 0) {
                $this->error('修改的值必须>=0');
            }
            Db::startTrans();
            $storage = StorageModel::find($sid);
            if (!$storage) {
                $this->error('仓库不存在');
            }
            $bool = StorageLogModel::where(['sid' => $sid, 'goods_id' => $goods_id])->find();
            if ($bool) {
                $r1 = $bool->save([$field => $value]);
            } else {
                $r1 = StorageLogModel::create([$field => $value, 'sid' => $sid, 'goods_id' => $goods_id, 'storage_name' => StorageModel::where('id', $sid)->value('store_name')]);
            }
            $r2 = true;
            if ($field == 'goods_num') {
                $total = StorageLogModel::where('goods_id', $goods_id)->sum('goods_num');
                $r2 = GoodsModel::update(['id' => $goods_id, 'goods_num' => $total]);
            }
            if ($r1 && $r2) {
                Db::commit();
                $this->success('修改成功');
            } else {
                Db::rollback();
                $this->error('修改失败');
            }
        }

        $goods = GoodsModel::find($request->id);
        
        $lst = StorageModel::where('mid', $goods['mid'])->where('is_del', 0)->order('id desc')->select()->toArray();
        foreach ($lst as $k => $item) {
            $log = StorageLogModel::where(['sid' => $item['id'], 'goods_id' => $request->id])->find();
            $list[$k]['goods_id'] = $request->id;
            $list[$k]['sid'] = $item['id'];
            $list[$k]['storage_name'] = $item['store_name'];
            $list[$k]['goods_num'] = $log ? $log['goods_num'] : 0;
            $list[$k]['freight_price'] = $item['price'];
        }
        $this->assign('list', $list);
        return $this->fetch();
    }
}